package concurrency;

/**
 * Created by Tzachi on 17/10/2014.
 * <p>
 * Pay attention to both volatile and double checked locking
 */
public class Singleton {
    /**
     * volatile in order to make sure that every thread will immediately notice the change in property
     */
    private static volatile Singleton uniqueInstance;

    /**
     * private constructor
     */
    private Singleton() {
    }

    public static Singleton getInstance() {
        // check if lock is needed
        if (uniqueInstance == null) {
            /**
             * critical section
             */
            synchronized (Singleton.class) {
                // second check for null instance, after lock was established
                if (uniqueInstance == null) {
                    uniqueInstance = new Singleton();
                }
            }
        }
        return uniqueInstance;
    }
}
